package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")

public class CommonController {


    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传-使用阿里云OSS
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("文件上传：{}",file);

        String originalFilename = file.getOriginalFilename();//文件原始名称
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//获取文件后缀

        //1.调用AliOssUtil工具类的upload方法上传文件
        String url = null;//文件上传
        try {
            String objectname= UUID.randomUUID().toString()+suffix;//生成随机文件名
            url = aliOssUtil.upload(file.getBytes(), objectname);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e.getMessage());
            return Result.error("上传失败");
        }

        return Result.success(url);
    }

}
